/* eslint-disable @typescript-eslint/no-unused-vars */
import { ProColumns, EditableProTable } from '@ant-design/pro-components';
import React, { useState, FC } from 'react';
import { Button } from 'antd';

type DataSourceType = {
  id: React.Key;
  title?: string;
  dataIndex?: string;
  width?: number | string;
};
interface IProps {
  value?: DataSourceType[];
  onChange?: (val: DataSourceType[]) => void;
}

const DefineColumns: FC<IProps> = ({ onChange, value: dataSource = [] }) => {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);

  const columns: ProColumns<DataSourceType>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      formItemProps: (form, { rowIndex }) => {
        return {
          rules: rowIndex > 1 ? [{ required: true, message: '此项为必填项' }] : [],
        };
      },
      width: 80,
    },
    {
      title: 'title',
      dataIndex: 'title',
      width: 200,
    },
    {
      title: 'dataIndex',
      dataIndex: 'dataIndex',
      width: 150,
    },
    {
      title: 'width',
      dataIndex: 'width',
      valueType: 'digit',
      width: 100,
    },
    {
      title: '操作',
      valueType: 'option',
      width: 200,
      align: 'center',
      render: (text, record, _, action) => [
        <Button
          key="editable"
          onClick={() => {
            action?.startEditable?.(record.id);
          }}
          type="primary"
        >
          编辑
        </Button>,
        <Button
          key="delete"
          onClick={() => {
            onChange?.(dataSource?.filter(item => item.id !== record.id) || []);
          }}
          danger
        >
          删除
        </Button>,
      ],
    },
  ];

  return (
    <>
      <EditableProTable<DataSourceType>
        rowKey="id"
        scroll={{ x: 600 }}
        maxLength={5}
        loading={false}
        columns={columns}
        request={async () => ({
          data: dataSource,
          total: 3,
          success: true,
        })}
        recordCreatorProps={{
          position: 'bottom',
          record: () => ({ id: `${dataSource.length + 1}` }),
        }}
        value={dataSource}
        onChange={onChange}
        editable={{
          type: 'multiple',
          editableKeys,
          onChange: setEditableRowKeys,
        }}
      />
    </>
  );
};
DefineColumns.defaultProps = {
  value: [],
  onChange: () => {},
};
export default DefineColumns;
